package com.ruoyi.lvlian.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.MD5Utils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.LhsOrderItem;
import com.ruoyi.lvlian.dto.LhsOrderDto;
import com.ruoyi.lvlian.dto.LhsOrderItemDto;
import com.ruoyi.lvlian.mapper.LhsOrderItemMapper;
import com.ruoyi.lvlian.util.OrderNumberGenerator;
import com.ruoyi.lvlian.vo.LhsOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.lvlian.mapper.LhsOrderMapper;
import com.ruoyi.lvlian.domain.LhsOrder;
import com.ruoyi.lvlian.service.ILhsOrderService;

/**
 * 莱回收订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class LhsOrderServiceImpl implements ILhsOrderService {
    @Autowired
    private LhsOrderMapper lhsOrderMapper;
    @Autowired
    private LhsOrderItemMapper lhsOrderItemMapper;

    /**
     * 查询莱回收订单
     *
     * @param id 莱回收订单主键
     * @return 莱回收订单
     */
    @Override
    public LhsOrderVo selectLhsOrderById(String id) {
        LhsOrderVo lhsOrder = lhsOrderMapper.selectLhsOrderById(id);
        if(lhsOrder!=null &&  StringUtils.isNotEmpty(lhsOrder.getOrderItems() ) &&StringUtils.isEmpty(lhsOrder.getOrderItems().get(0).getOrderItemId() ) ){
            lhsOrder.setOrderItems(null);
        }
        return lhsOrder;
    }

    /**
     * 查询莱回收订单列表
     *
     * @param lhsOrder 莱回收订单
     * @return 莱回收订单
     */
    @Override
    public List<LhsOrderVo> selectLhsOrderList(LhsOrderDto Order) {
        List<LhsOrderVo> lhsOrderVos = lhsOrderMapper.selectLhsOrderList(Order);

        for(    LhsOrderVo vo: lhsOrderVos  ){
            if(vo!=null &&  StringUtils.isNotEmpty(vo.getOrderItems() ) &&StringUtils.isEmpty(vo.getOrderItems().get(0).getOrderItemId() ) ){
                vo.setOrderItems(null);
            }
        }


        return lhsOrderVos;
    }


    @Override
    public LhsOrder insertLhsOrder(LhsOrder orderInfo) {
        if (StringUtils.isEmpty(orderInfo.getOrderNum())) {
            orderInfo.setOrderNum(OrderNumberGenerator.generateOrderNumber());
        }

        orderInfo.setId(MD5Utils.md5(orderInfo.getOrderNum()));
        orderInfo.setCreateUser(SecurityUtils.getUsername());
        orderInfo.setCreateDate(DateUtils.getCurrentTime());
        lhsOrderMapper.insertLhsOrder(orderInfo);

        return orderInfo;
    }

    /**
     * 修改莱回收订单
     *
     * @param lhsOrder 莱回收订单
     * @return 结果
     */
    @Override
    public LhsOrder updateLhsOrder(LhsOrder lhsOrder) {

        LhsOrder updateResult =  new LhsOrder();
        if (StringUtils.isEmpty(lhsOrder.getId())) {
            updateResult = insertLhsOrder(lhsOrder);
        } else {
            lhsOrder.setCreateDate(DateUtils.getCurrentTime());
            lhsOrderMapper.updateLhsOrder(lhsOrder);
        }
        updateResult=  lhsOrderMapper.selectLhsOrderOnlyById(lhsOrder.getId());


        return updateResult;

    }

    /**
     * 批量删除莱回收订单
     *
     * @param ids 需要删除的莱回收订单主键
     * @return 结果
     */
    @Override
    public int deleteLhsOrderByIds(String[] ids) {
        return lhsOrderMapper.deleteLhsOrderByIds(ids);
    }

    /**
     * 删除莱回收订单信息
     *
     * @param id 莱回收订单主键
     * @return 结果
     */
    @Override
    public int deleteLhsOrderById(String id) {
        return lhsOrderMapper.deleteLhsOrderById(id);
    }

    @Override
    public Map<String, Object> getDailyRevenue(LhsOrderDto lhsOrder) {
        return lhsOrderMapper.getDailyRevenue(lhsOrder);
    }

    @Override
    public Map<String, Object> getDailyAveragePrice(LhsOrderDto lhsOrder) {
        return lhsOrderMapper.getDailyAveragePrice(lhsOrder);
    }

    @Override
    public Map<String, Object> queryOrdeInfoByCategory(LhsOrderDto lhsOrder) {
        Map<String, Object> orderMap = new HashMap<>();

        // 定义必须包含的分类列表
        List<String> requiredCategories = Arrays.asList("废金属", "废塑料", "废纸", "废玻璃", "废纺织");

        // 查询并补全指定日期的订单数据
        List<HashMap<String, Object>> orderSingleDate = completeMissingCategories(
                lhsOrderMapper.queryOrdePriceByCategory(lhsOrder), requiredCategories);

        // 查询并补全汇总数据
        lhsOrder.setCreateDate(null);
        List<HashMap<String, Object>> orderList = completeMissingCategories(
                lhsOrderMapper.queryOrdePriceByCategory(lhsOrder), requiredCategories);

        orderMap.put("singleDate", orderSingleDate);
        orderMap.put("summary", orderList);
        return orderMap;
    }

    /**
     * 补全缺失的分类
     */
    private List<HashMap<String, Object>> completeMissingCategories(List<HashMap<String, Object>> dataList,
                                                                    List<String> requiredCategories) {
        List<HashMap<String, Object>> result = dataList != null ? new ArrayList<>(dataList) : new ArrayList<>();

        // 获取现有分类名称
        Set<String> existingCategories = result.stream()
                .map(item -> item.get("categoryLevelName1"))
                .filter(Objects::nonNull)
                .map(Object::toString)
                .collect(Collectors.toSet());

        // 添加缺失的分类，数值字段设置为0
        requiredCategories.stream()
                .filter(category -> !existingCategories.contains(category))
                .forEach(category -> {
                    HashMap<String, Object> defaultData = new HashMap<>();
                    defaultData.put("categoryLevelName1", category);
                    defaultData.put("netWeight", 0);
                    defaultData.put("sumPrice", 0);
                    defaultData.put("avgPrice", 0);
                    defaultData.put("cnt", 0);
                    result.add(defaultData);
                });

        return result;
    }

    @Override
    public List<LhsOrderVo> getAllOrdersWithItems(LhsOrderDto lhsOrderDto) {
        // 查询订单
        List<LhsOrderVo> orders = lhsOrderMapper.selectLhsOrderList(lhsOrderDto);

        // 获取所有订单ID
        List<String> orderIds = orders.stream()
                .map(LhsOrder::getId)
                .collect(Collectors.toList());

        if (!orderIds.isEmpty()) {
            // 查询这些订单的所有订单项
            List<LhsOrderItem> orderItems = lhsOrderItemMapper.selectOrderItemsByOrderIds(orderIds);

            // 将订单项按订单ID分组
            Map<String, List<LhsOrderItem>> orderItemsMap = orderItems.stream()
                    .collect(Collectors.groupingBy(LhsOrderItem::getOrderNum));

            // 将订单项设置到对应的订单中
            for (LhsOrderVo order : orders) {
                order.setOrderItems(orderItemsMap.get(order.getId()));
            }
        }

        return orders;
    }

    @Override
    public Map<String, Object> queryOrdeInfoSummaryByPad(LhsOrderDto lhsOrder) {
        return lhsOrderMapper.queryOrdeInfoSummaryByPad(lhsOrder);
    }

    @Override
    public Map<String, Object> queryOrdeInfoByAmount(LhsOrderDto lhsOrder) {

        Map<String, Object> orderMap = new HashMap<>();
        Map<String, Object> cnt = lhsOrderMapper.queryOrdeInfoCntByAmount(lhsOrder);
        if (cnt == null || cnt.size() < 1) {
            cnt = new HashMap<>();
            // 定义需要确保存在的键及其默认值
            cnt.put("bigCnt", 0);
            cnt.put("middleCnt", 0);
            cnt.put("smallCnt", 0);
        }
        Map<String, Object> price = lhsOrderMapper.queryOrdeInfoPriceByAmount(lhsOrder);


        if (price == null || price.size() < 1) {
            price = new HashMap<>();
            // 定义需要确保存在的键及其默认值
            price.put("bigPrice", 0);
            price.put("middlePrice", 0);
            price.put("smallPrice", 0);
        }
        orderMap.put("cnt", cnt);
        orderMap.put("price", price);


        return orderMap;
    }

    @Override
    public Map<String, List<LhsOrderVo>> queryOrderListByProductName(LhsOrderDto lhsOrder) {
        List<LhsOrderVo> lhsOrderVos = lhsOrderMapper.queryOrderListByProductName(lhsOrder);

        if (lhsOrderVos == null || lhsOrderVos.isEmpty()) {
            return Collections.emptyMap();
        }

        // 直接按产品名称分组
        Map<String, List<LhsOrderVo>> groupedByProductName = lhsOrderVos.stream()
                .filter(order -> order != null && order.getOrderNum() != null)
                .collect(Collectors.groupingBy(LhsOrderVo::getOrderNum));


        return groupedByProductName;
    }

    @Override
    public     LhsOrderVo   queryCartOrderItemByMac(LhsOrderItemDto dto) {
        return lhsOrderMapper.queryCartOrderItemByMac(dto);
    }
}
